import { SelectQueryBuilder } from "typeorm";
import { Workbook, Worksheet } from 'exceljs';
import * as moment from "moment";
// 获取分页数据
export async function getPageResult(index, size, queryBuilder: SelectQueryBuilder<any>) {
    const skip: number = (index-1) * size;
    const take: number = size;
    const list = await queryBuilder
    .offset(skip)
    .limit(take)
    .getRawMany()
    const total = await queryBuilder.getCount()
    return {
      list: list,
      page: index, // 当前页码
      pageSize: list.length, // 查询条数
      next: index * size < total, // 是否有下一页
      total: total,
    }
}
/**
 * 
 * @param Headers 
 * 实列：{ prop: 'id', name: '编号'},
        { prop: 'status', name: '借阅状态', format: {'0':'再借', '1': '已归还', '2': '逾期'}},
        { prop: 'borrow_date', name: '借阅时间', datetime: true, customFormat: 'YYYY-MM-DD hh:mm:ss'},
 * @param data 
   实列：[{id:'1', status:0,borrow_date:'121545655'}]
 * @param res 响应器
 */
// 导出excel
export async function exportToExcel(Headers: Array<{prop: string, name: string}|any>, data: any[], res): Promise<void> {
  const workbook = new Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');
  // 添加标题行
  // worksheet.addRow([...headerTitles]);
  const headerRow = worksheet.getRow(1);
  Headers.forEach((v, i) => {
    headerRow.getCell(i+1).value = v.name
    headerRow.getCell(i+1).font = { bold: true };
    headerRow.getCell(i+1).fill = { type: 'pattern', pattern:'solid', fgColor:{argb:'FFFFAA00'} }; // 背景色
    headerRow.getCell(i+1).border = { top: { style: 'thin' }, left: { style: 'thin', }, bottom: { style: 'thin' }, right: { style: 'thin' } }; // 边框
  })
  // 添加数据行
  data.forEach((row, index) => {
    const sheetRow = worksheet.getRow(index+2);
    Headers.forEach((header, i) => {
      let val = row[header.prop]
      if (header.datetime) { // 实际格式化
        if (header.customFormat) {
          val = moment(row[header.prop]).format(header.customFormat)
        } else {
          val = moment(row[header.prop]).format('YYYY-MM-DD hh:mm:ss')
        }
      } else if (header.format) { // 状态值转换 
        val = header.format[row[header.prop]]
      }
      sheetRow.getCell(i+1).value = val
      sheetRow.getCell(i+1).border = { top: { style: 'thin' }, left: { style: 'thin', }, bottom: { style: 'thin' }, right: { style: 'thin' } }; // 边框
    })
    // worksheet.addRow([...values]);
  });
  // 写入到文件
  await workbook.xlsx.write(res);
}